<template>
  <a-modal
    :open="open"
    width="1000px"
    title="理疗预约维护"
    centered
    :ok-button-props="{ disabled: !isCompleted || selectedRowKeys.length === 0 }"
    ok-text="保存"
    destroy-on-close
    @ok="onOk"
    @cancel="onCancel"
  >
    <div class="flex">
      <div class="w-1/2 form-style-flex">
        <a-form :model="formState" class="form-style-flex">
          <a-form-item label="姓名" name="brName" class="w-full" v-bind="validateInfos.brName">
            <SelectTable v-model:value="formState.brName" type="理疗非预约" custom-input empty-close @select="onChangeUser" />
          </a-form-item>
          <UserCard :user-data="formState" style="padding-left: 86px">
            <a-descriptions class="mt-3 ml-5" :column="1">
              <a-descriptions-item label="联系地址" class="w-full"> {{ formState?.brLxrdz || '-' }}</a-descriptions-item>
              <a-descriptions-item label="最近服务" class="w-full">
                <div class="flex w-full justify-between">
                  <div class="w-1/2">{{ formState?.endTime || '-' }}</div>
                  <div class="w-1/2">{{ formState?.itemName || '-' }}</div>
                </div>
              </a-descriptions-item>
              <a-descriptions-item label="最近医师" class="w-full"> {{ formState?.zxys || '-' }}</a-descriptions-item>
            </a-descriptions>
          </UserCard>

          <!-- <a-form-item name="xb" label="性别" class="w-1/2">
            <a-input v-model:value="formState.brXb" disabled placeholder="请输入" />
          </a-form-item>
          <a-form-item name="nl" label="年龄" class="w-1/2">
            <a-input v-model:value="formState.brAge" disabled placeholder="请输入" />
          </a-form-item>
          <a-form-item name="phone" label="手机" class="w-full">
            <a-input v-model:value="formState.brMob" disabled placeholder="请输入" />
          </a-form-item>
          <a-form-item name="brkh" label="卡号" class="w-full">
            <a-input v-model:value="formState.brId" disabled placeholder="请输入" />
          </a-form-item> -->
          <a-form-item label="备注" class="w-full mt-4">
            <a-textarea v-model:value="formState.memo" :rows="10" placeholder="请输入" />
          </a-form-item>
        </a-form>
      </div>
      <div class="w-1/2 pl-3">
        <div class="w-full flex">
          <a-form-item name="yyrq" label="预约日期" class="w-2/3" v-bind="validateInfos.yyrq">
            <a-date-picker v-model:value="formState['yyrq']" :disabled-date="disabledDate" class="w-full" value-format="YYYY-MM-DD" placeholder="请选择" />
          </a-form-item>
          <a-form-item name="yysj" label="" class="w-1/3 pl-2" v-bind="validateInfos.yysj">
            <!-- <a-time-picker v-model:value="formState.yysj" value-format="HH:mm" class="w-full" /> -->
            <a-input v-model:value="formState.yysj" class="w-full" placeholder="请输入" />
          </a-form-item>
        </div>
        <a-form-item name="empName" label="预约医师" class="w-full" v-bind="validateInfos.empName">
          <SelectTable v-model:value="formState.empName" type="预约医师" @select="onSelectDoctor" />
        </a-form-item>
        <a-form-item name="yyfs" label="预约方式" class="w-full">
          <a-select v-model:value="formState.yyfs" class="" :options="yyfsoption" />
        </a-form-item>
        <BaseTable
          :data-source="dataSource"
          height="292"
          row-key="itemCode"
          :row-selection="{ selectedRowKeys, onChange: onCheckChange }"
          :columns="columns"
          :row-class-name="(record) => (record.isNew ? 'table-row-new' : '')"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'sl'">
              <EditCell title="预约次数">
                <a-input v-model:value="record.sl" v-input:int class="!text-right" placeholder="请输入" @change="onChangeSl(record)" />
              </EditCell>
            </template>
            <template v-if="column.dataIndex === 'cmemo'">
              <EditCell title="备注">
                <a-input v-model:value="record.memo" placeholder="请输入" />
              </EditCell>
            </template>
          </template>
        </BaseTable>
      </div>
    </div>
  </a-modal>
</template>
<script setup>
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { post } from '@/utils/request'
import UserCard from '@/components/UserCard'

const emit = defineEmits(['update:open', 'success'])
const dataSource = ref([])
const yyfsoption = ref([
  {
    lebel: '当场预约',
    value: '当场预约'
  },
  {
    lebel: '电话预约',
    value: '电话预约'
  },
  {
    lebel: '微信预约',
    value: '微信预约'
  },
  {
    lebel: '第三方平台预约',
    value: '第三方平台预约'
  },
  {
    lebel: '其他预约',
    value: '其他预约'
  }
])
const selectedRowKeys = ref([])
const selectedRowData = ref([])
const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => ({})
  },
  title: {
    type: String,
    default: ''
  }
})
const columns = ref([
  { title: '服务项目', dataIndex: 'itemName' },
  { title: '剩余次数', dataIndex: 'sysl', align: 'right' },
  { title: '预约次数', dataIndex: 'sl', align: 'right' },
  { title: '备注', dataIndex: 'cmemo' }
])

const formState = ref({
  brName: '',
  yyrq: '',
  yysj: '',
  empName: '',
  yyfs: '',
  brXb: '',
  brAge: '',
  brMob: '',
  brId: '',
  memo: ''
})
const rulesState = ref({
  brName: [{ required: true, message: '请选择患者' }],
  yyrq: [{ required: true, message: '请选择到场日期' }],
  yysj: [{ required: true, message: '请选择预约时间' }],
  empName: [{ required: true, message: '请选择医生' }]
})
const disabledDate = (current) => {
  // 获取今天的日期
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  // 将当前日期与今天的日期进行比较
  return current && current < today
}
const onChangeSl = (record) => {
  if (parseInt(record.sl) <= 0) record.sl = 1
  if (parseInt(record.sl) > record.sysl) {
    record.sl = record.sysl
  }
}
const getTableCheck = async (lsh) => {
  const res = await post('/course/serviceItemAssociation/getCourseAppointment', { lsh })
  if (res.code !== 0) return message.error(res.msg)
  selectedRowData.value = res.data.courseAppointmentDetailList
  selectedRowKeys.value = res.data.courseAppointmentDetailList.map((item) => item.itemCode)
  dataSource.value = dataSource.value.map((item) => {
    const thisItem = res.data.courseAppointmentDetailList.find((list) => list.itemCode === item.itemCode)
    if (thisItem) {
      item = thisItem
    }
    return item
  })
  // dataSource.value = [...new Set([...res.data.courseAppointmentDetailList, ...dataSource.value])]
}

const onSelectDoctor = (data) => {
  formState.value = {
    ...formState.value,
    ...data
  }
}
const onCheckChange = (keys, data) => {
  selectedRowKeys.value = keys
  selectedRowData.value = data
}

const getTableData = async (brId) => {
  const res = await post('course/serviceItemAssociation/getCourseServiceItemServiceList', { brId })
  if (res.code !== 0) return message.error(res.msg)
  dataSource.value = res.data.map((item) => {
    return {
      sl: 1,
      ...item
    }
  })
}
const { isCompleted, resetFields, validate, validateInfos } = useForm(formState, rulesState)
watch(
  () => props.open,
  (val) => {
    if (val) {
      if (props.rowData?.lsh) {
        formState.value = { ...props.rowData }
        getTableData(formState.value.brId)
        getTableCheck(props.rowData.lsh)
      } else {
        formState.value = {}
        dataSource.value = []
        selectedRowKeys.value = []
        selectedRowData.value = []
      }
    }
  }
)

const onOk = async () => {
  await validate()
  // return
  formState.value = {
    courseAppointmentDetailList: selectedRowData.value,
    ...formState.value
  }
  const res = await post('/course/serviceItemAssociation/doSaveCourseAppointment', formState.value)
  if (res.code === 0) {
    message.success(res.msg)

    emit('success')
    onCancel()
  } else {
    message.error(res.msg)
  }
}
const onChangeUser = (data) => {
  formState.value = {
    ...formState.value,
    ...data
  }
  getTableData(data.brId)
}

const onCancel = () => {
  emit('update:open', false)
  resetFields()
}
</script>
<style lang="less" scoped></style>
